package org.f0rb.demo.web;

import org.f0rb.core.web.WebContext;
import org.f0rb.demo.common.CONSTANT;
import org.f0rb.demo.model.user.User;
import org.f0rb.demo.utils.RequestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Class org.f0rb.demo._ description goes here.
 *
 * @author Administrator
 * @version 1.0.0 11-9-17
 */
public class Context {
    private final static Logger LOGGER = LoggerFactory.getLogger(Context.class);

    @SuppressWarnings("unused")
    private Context() {}

    public static HttpServletRequest getRequest() {
        return WebContext.getRequest();
    }

    public static HttpServletResponse getResponse() {
        return WebContext.getResponse();
    }

    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    public static HttpSession getSession(boolean create) {
        return getRequest().getSession(create);
    }

    /**
     * 将inactiveUserDTO存入session中.
     * <p/>
     * 在以下几种情况下，将inactiveUserDTO注入到session
     * 1.用户注册后
     * 2.登录但是用户未激活
     * 3.忘记密码但是用户未激活
     *
     * @param inactiveUserDTO 未激活的用户，至少包含username, token, serviceName
     */
    public static void setInactiveUser(final User inactiveUserDTO) {
        getSession().setAttribute(CONSTANT.SESSION.INACTIVE_USER, inactiveUserDTO.toSessionUser());
    }

    public static User getInactiveUser() {
        return (User) getSession().getAttribute(CONSTANT.SESSION.INACTIVE_USER);
    }

    /**
     * 将inactiveUserDTO从session中移除
     * <p/>
     * 在以下几种情况下，将inactiveUserDTO从session中移除
     * 1.登录成功
     * 1.1 点击激活链接自动登录
     * 1.2 使用其他已激活帐号登录
     * 2.session过期
     */
    public static void removeInactiveUser() {
        getSession().removeAttribute(CONSTANT.SESSION.INACTIVE_USER);
    }

    public static void setLoginUser(final User loginUserDTO) {
        setLoginUser(getSession(), loginUserDTO);
    }

    public static void setLoginUser(HttpSession session, final User loginUserDTO) {
        if (session != null) {
            session.setAttribute(CONSTANT.SESSION.LOGIN_USER, loginUserDTO.toSessionUser());
        } else {
            LOGGER.warn("Session is null!");
        }
    }

    public static User getLoginUser() {
        return (User) getSession().getAttribute(CONSTANT.SESSION.LOGIN_USER);
    }

    public static User getLoginUser(HttpSession session) {
        if (session == null) {
            LOGGER.warn("Session is null!");
            return null;
        }
        return (User) session.getAttribute(CONSTANT.SESSION.LOGIN_USER);
    }

    public static void removeLoginUser() {
        getSession().removeAttribute(CONSTANT.SESSION.LOGIN_USER);
    }

    public static void setLoginCookies(final User o) {
        HttpServletRequest request = getRequest();
        HttpServletResponse response = getResponse();
        int maxAge = Boolean.TRUE.equals(o.getAutologin()) ? CONSTANT.COOKIE.HOLD_DAY : -1;
        response.addCookie(RequestUtils.createCookie(request, CONSTANT.COOKIE.LAST_LOGIN,
                String.format("%s", o.getLastlogin()), -1));
        response.addCookie(RequestUtils.createCookie(request, CONSTANT.COOKIE.ACCOUNT, o.getAccount(), maxAge));
        String nickname;
        try {
            nickname = URLEncoder.encode(o.nickname, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            nickname = o.nickname;
            LOGGER.warn(e.getMessage());
        }
        response.addCookie(RequestUtils.createCookie(request, CONSTANT.COOKIE.NICKNAME, nickname, maxAge));
    }

    public static void clearLoginCookies() {
        HttpServletRequest request = getRequest();
        HttpServletResponse response = getResponse();
        response.addCookie(RequestUtils.createCookie(request, CONSTANT.COOKIE.ACCOUNT, "", 0));
        response.addCookie(RequestUtils.createCookie(request, CONSTANT.COOKIE.LAST_LOGIN, "", 0));
        response.addCookie(RequestUtils.createCookie(request, CONSTANT.COOKIE.NICKNAME, "", 0));
    }
}
